package com.lc.recovery.ui.activity.recoverymine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.recovery.R;
import com.lc.recovery.app.AppActivity;
import com.lc.recovery.http.glide.GlideApp;
import com.lc.recovery.http.request.UpdateAvatarApi;
import com.lc.recovery.http.request.UpdateImageApi;
import com.lc.recovery.http.request.UpdateUserApi;
import com.lc.recovery.http.response.PublicMsg;
import com.lc.recovery.http.response.UpdateAvatarBean;
import com.lc.recovery.http.response.UpdateImageBean;
import com.lc.recovery.other.AppConfig;
import com.lc.recovery.other.IntentKey;
import com.lc.recovery.ui.activity.ImageSelectActivity;
import com.lc.recovery.ui.dialog.InputDialog;
import com.lc.recovery.util.CourseUtils;
import com.lc.recovery.util.SPUtil;
import com.lc.widget.layout.SettingBar;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonalCenterActivity extends AppActivity {
    @BindView(R.id.iv_person_data_avatar)
    ImageView ivPersonDataAvatar;
    @BindView(R.id.fl_person_data_avatar)
    SettingBar flPersonDataAvatar;

    @BindView(R.id.sb_person_data_name)
    SettingBar sbPersonDataName;


    @BindView(R.id.btn_keep)
    AppCompatButton btnKeep;
    @BindView(R.id.sb_person_phone)
    SettingBar sbPersonPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    /**
     * 省
     */
    private String mProvince = "";
    /**
     * 市
     */
    private String mCity = "";
    /**
     * 区
     */
    private String mArea = "";

    /**
     * 头像地址
     */
    private String mAvatarUrl;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_personalcenter;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);

        GlideApp.with(getActivity())
                .load(SPUtil.get(this, IntentKey.IMAGE, ""))
                .placeholder(R.mipmap.avatar_placeholder_ic)
                .error(R.mipmap.avatar_placeholder_ic)
                .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                .into(ivPersonDataAvatar);
        sbPersonPhone.setRightText(SPUtil.get(this, IntentKey.PHONE, ""));

        sbPersonDataName.setRightText(SPUtil.get(this, IntentKey.NAME, ""));
        if (CourseUtils.isNotNullOrEmpty(SPUtil.get(this, IntentKey.USERID, ""))) {
            etAddress.setText(SPUtil.get(this, IntentKey.ADDRESS, ""));

        }

        if (SPUtil.get(this, IntentKey.TYPE, "").equals("1")) {

            rlAddress.setVisibility(View.VISIBLE);
            tvAddress.setText("商户地址");
        } else if (SPUtil.get(this, IntentKey.TYPE, "").equals("2")) {

            rlAddress.setVisibility(View.VISIBLE);
            tvAddress.setText("社区地址");
        }else {
            rlAddress.setVisibility(View.GONE);
        }

//        String address = SPUtil.get(this, IntentKey.ADDRESS, "");
//        sbPersonDataAddress.setRightText(address);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        String address = SPUtil.get(this, IntentKey.ADDRESS, "");
//        sbPersonDataAddress.setRightText(address);
    }

    @OnClick({R.id.iv_person_data_avatar, R.id.fl_person_data_avatar, R.id.sb_person_data_name, R.id.btn_keep})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_person_data_avatar:
                ImageSelectActivity.start(this, data -> {
                    // 裁剪头像

                    cropImage(new File(data.get(0)));
                });
                break;
            case R.id.fl_person_data_avatar:
                break;

            case R.id.sb_person_data_name:
                new InputDialog.Builder(this)
                        // 标题可以不用填写
                        .setTitle(getString(R.string.personal_data_name_hint))
                        .setContent(sbPersonDataName.getRightText())
                        //.setHint(getString(R.string.personal_data_name_hint))
                        //.setConfirm("确定")
                        // 设置 null 表示不显示取消按钮
                        //.setCancel("取消")
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener((dialog, content) -> {
                            if (!sbPersonDataName.getRightText().equals(content)) {
                                sbPersonDataName.setRightText(content);
                            }
                        })
                        .show();
                break;


            case R.id.btn_keep:
//                保存
                if (SPUtil.get(this, IntentKey.TYPE, "").equals("1")||SPUtil.get(this, IntentKey.TYPE, "").equals("2")){
                    updateUser();
                }else {
                    updateUserelse();
                }

                finish();
                break;
        }
    }

    private void updateUserelse() {
        EasyHttp.post(this)
                .api(new UpdateUserApi()
                        .setUser_id(SPUtil.get(PersonalCenterActivity.this, IntentKey.USERID, "")).setReal_name(sbPersonDataName.getRightText().toString()).setType(SPUtil.get(this, IntentKey.TYPE, "")))
                .request(new HttpCallback<PublicMsg>(PersonalCenterActivity.this) {

                    @Override
                    public void onSucceed(PublicMsg data) {
                        if (data.getCode() == 200) {
                            toast("保存成功");
                            SPUtil.put(getContext(),IntentKey.ADDRESS,etAddress.getText().toString());

                            finish();
                        }
                    }
                });
    }

    private void updateUser() {
        if (etAddress.getText().toString().trim().isEmpty()) {
            toast("请输入详细地址");
            return;
        }
        EasyHttp.post(this)
                .api(new UpdateUserApi()
                        .setUser_id(SPUtil.get(PersonalCenterActivity.this, IntentKey.USERID, "")).setReal_name(sbPersonDataName.getRightText().toString()).setAddress(etAddress.getText().toString()).setType(SPUtil.get(this, IntentKey.TYPE, "")))
                .request(new HttpCallback<PublicMsg>(PersonalCenterActivity.this) {

                    @Override
                    public void onSucceed(PublicMsg data) {
                        if (data.getCode() == 200) {
                            toast("保存成功");
                            SPUtil.put(getContext(),IntentKey.ADDRESS,etAddress.getText().toString());

                            finish();
                        }
                    }
                });
    }

    private void cropImage(File sourceFile) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(getContext(), AppConfig.getPackageName() + ".provider", sourceFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(sourceFile);
        }

        String regex = "^(.+)(\\..+)$";
        String fileName = sourceFile.getName().replaceFirst(regex, "$1_crop_" + new SimpleDateFormat("HHmmss", Locale.getDefault()).format(new Date()) + "$2");

        File outputFile = new File(sourceFile.getParent(), fileName);
        if (outputFile.exists()) {
            outputFile.delete();
        }

        intent.setDataAndType(uri, "image/*");
        // 是否进行裁剪
        intent.putExtra("crop", String.valueOf(true));
        // 宽高裁剪比例
        if (Build.MANUFACTURER.toUpperCase().contains("HUAWEI")) {
            // 华为手机特殊处理，否则不会显示正方形裁剪区域，而是显示圆形裁剪区域
            // https://blog.csdn.net/wapchief/article/details/80669647
            intent.putExtra("aspectX", 9998);
            intent.putExtra("aspectY", 9999);
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        // 是否裁剪成圆形（注：在华为手机上没有任何效果）
        // intent.putExtra("circleCrop", false);
        // 宽高裁剪大小
        // intent.putExtra("outputX", 200);
        // intent.putExtra("outputY", 200);
        // 是否保持比例不变
        intent.putExtra("scale", true);
        // 裁剪区域小于输出大小时，是否放大图像
        intent.putExtra("scaleUpIfNeeded", true);
        // 是否将数据以 Bitmap 的形式保存
        intent.putExtra("return-data", false);
        // 设置裁剪后保存的文件路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outputFile));
        // 设置裁剪后保存的文件格式
        intent.putExtra("outputFormat", getImageFormat(sourceFile).toString());

        // 判断手机是否有裁剪功能
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, (resultCode, data) -> {
                if (resultCode == RESULT_OK) {
                    updateImage(outputFile, true);
                }
            });
            return;
        }

        // 没有的话就不裁剪，直接上传原图片
        // 但是这种情况极其少见，可以忽略不计
        updateImage(sourceFile, false);
    }

    /**
     * 上传图片
     */
    private void updateImage(File file, boolean deleteFile) {


        EasyHttp.post(this)
                .api(new UpdateImageApi()
                        .setPicurl(file))
                .request(new HttpCallback<UpdateImageBean>(PersonalCenterActivity.this) {

                    @Override
                    public void onSucceed(UpdateImageBean data) {
                        if (data.getCode() == 200) {
                            updateAvatar(data.getData().getUrl(), deleteFile);

                        }

                    }
                });
    }

    private void updateAvatar(String url, boolean deleteFile) {
        EasyHttp.post(this)
                .api(new UpdateAvatarApi()
                        .setUrl(url).setType(SPUtil.get(this, IntentKey.TYPE, "")).setUser_id(SPUtil.get(this, IntentKey.USERID, "")))
                .request(new HttpCallback<UpdateAvatarBean>(PersonalCenterActivity.this) {

                    @Override
                    public void onSucceed(UpdateAvatarBean data) {
                        if (data.getCode() == 200) {

                            mAvatarUrl = data.getUrl();
                            SPUtil.put(PersonalCenterActivity.this, IntentKey.IMAGE, mAvatarUrl);
                            GlideApp.with(getActivity())
                                    .load(mAvatarUrl)
                                    .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                    .into(ivPersonDataAvatar);

                        }

                    }
                });
    }

    /**
     * 获取图片文件的格式
     */
    private Bitmap.CompressFormat getImageFormat(File file) {
        String fileName = file.getName().toLowerCase();
        if (fileName.endsWith(".png")) {
            return Bitmap.CompressFormat.PNG;
        } else if (fileName.endsWith(".webp")) {
            return Bitmap.CompressFormat.WEBP;
        }
        return Bitmap.CompressFormat.JPEG;
    }


}
